<?php
require_once('core/core.php');
require_once('swift/swift_required.php');

$pidfile = '/var/run/php-sender.pid';

if ( file_exists($pidfile) )
{
    if ( $pid = file($pidfile) )
    {
	if ( !is_dir(sprintf('/proc/%d',$pid[0])) )
	{
	    error_log(sprintf("PID-file found, but proccess with PID#%d not found!\n",$pid));

	    $pid = getmypid();

	    error_log(sprintf("Overwriting PID-file, new pid is %d\n",$pid));
	    $fh = fopen($pidfile,'w');
	    fwrite($fh,$pid);
	    fclose($fh);
	}
	else
	{
	    die();
//	    die("Another proccess of sender running now...\n");
	}
    }
    else
    {
	die("PID-file exists but we can not read it!\nterminating...\n\n");
    }
}
else
{
    $pid = getmypid();

    $fh = fopen($pidfile,'w');
    fwrite($fh,$pid);
    fclose($fh);
}

$db = new DB;

$mQuery=
    'SELECT '
	.'`mq`.`id`,'
	.'`mq`.`executive_id`,'
	.'`mq`.`message`,'
	.'`e`.`email_smtp`,'
	.'`e`.`email_smtp_port`,'
	.'`e`.`email_smtp_ssl`,'
	.'`e`.`email_login`,'
	.'`e`.`email_password`'
    .' FROM `mail_queue` mq'
    .' JOIN `executive` e ON `e`.`id`=`mq`.`executive_id`'
    .' WHERE `status` IN(0)'
    .' ORDER BY `mq`.`id`,`mq`.`executive_id`';

if ( $result = $db->_doQuery($mQuery) )
{
    while ( $row = mysql_fetch_assoc($result) )
    {
	usleep(200000);
	if ( !isset($transport[$row['executive_id']]) )
	{
	    $transport[$row['executive_id']] = Swift_SmtpTransport::newInstance($row['email_smtp'], intval($row['email_smtp_port']), ($row['email_smtp_ssl']==1)?'ssl':NULL);

	    if ( !empty($row['email_login']) )
	    {
		$transport[$row['executive_id']]->setUsername($row['email_login']);

		if ( !empty($row['email_password']) )
		{
		    $transport[$row['executive_id']]->setPassword($row['email_password']);
		}
	    }

	    $mailer = Swift_Mailer::newInstance($transport[$row['executive_id']]);
	}

	$message = unserialize(base64_decode($row['message']));

	if ( !isset($mailer) ) { die('Instance of mailer not defined!'); }

	//$db->_doQuery(sprintf('UPDATE `mail_queue` SET `status`=1 WHERE `id`=%d',$row['id']));
	//$db->_doQuery(sprintf('DELETE FROM `mail_queue` WHERE `id`=%d',$row['id']));
	
	$db->_doQuery(sprintf('UPDATE `mail_queue` SET `status`=3 WHERE `id`=%d',$row['id']));

	printf("Processing ID#%d...\n",$row['id']);
	//printf("sending message %s\n",$row['email_login']);
	if ( $mailer->send($message,$fail) )
	{
	    $db->_doQuery(sprintf('UPDATE `mail_queue` SET `status`=2 WHERE `id`=%d',$row['id']));
	    //$db->_doQuery(sprintf('DELETE FROM `mail_queue` WHERE `id`=%d',$row['id']));
	    print_r ("message send\n");
	}
	else
	{
	    //$db->_doQuery(sprintf('DELETE FROM `mail_queue` WHERE `id`=%d',$row['id']));
	    print_r ("message send fail\n");
	    print_r($fail);
	}
    }
}

//sleep(20);
unlink($pidfile);
die( mysql_error() );
?>
